# -*- coding: utf-8 -*-

from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.utils.html import strip_tags
from markdown import Markdown


class Category(models.Model):
    """分类"""
    name = models.CharField(verbose_name=u'分类名称', max_length=100)

    class Meta:
        db_table = 'mb_category'
        verbose_name = u'分类'
        verbose_name_plural = u'分类'

    def __unicode__(self):
        return self.name


class Tag(models.Model):
    """标签"""
    name = models.CharField(verbose_name=u'标签名称', max_length=100)

    class Meta:
        db_table = 'mb_tag'
        verbose_name = u'标签'
        verbose_name_plural = u'标签'

    def __unicode__(self):
        return self.name


class Article(models.Model):
    """文章"""
    title = models.CharField(verbose_name=u'标题', max_length=70)
    body = models.TextField(verbose_name=u'正文')
    created_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    modified_time = models.DateTimeField(verbose_name=u'修改时间', auto_now=True)
    summary = models.CharField(verbose_name=u'摘要', max_length=200, blank=True)
    category = models.ForeignKey(Category, verbose_name=u'分类')
    tag = models.ManyToManyField(Tag, blank=True, verbose_name=u'标签')
    author = models.ForeignKey(User, verbose_name=u'作者')
    views = models.PositiveIntegerField(verbose_name=u'文章阅读量', default=0)

    class Meta:
        db_table = 'mb_article'
        verbose_name = u'文章'
        verbose_name_plural = u'文章'
        ordering = ['-created_time']

    def get_absolute_url(self):
        return reverse('myblog:detail', kwargs={'pk': self.pk})

    def increase_views(self):
        """阅读量 +1"""
        self.views += 1
        self.save(update_fields=['views'])

    def save(self, *args, **kwargs):
        if not self.summary:
            md = Markdown(
                extensions=[
                    'markdown.extensions.extra',
                    'markdown.extensions.codehilite',
                ])
            self.summary = strip_tags(md.convert(self.body))[:180]
        super(Article, self).save(*args, **kwargs)
